package com.juzipi.demo.handler;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.juzipi.demo.pojo.User;
import com.juzipi.demo.tools.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


//自定义登录成功后处理
public class JsonLoginSuccessHandler implements AuthenticationSuccessHandler {


    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //authentication 是 UsernamePasswordAuthenticationToken
        //getPrincipal 是 登陆用户的信息
        User user = (User) authentication.getPrincipal();
        Result result = Result.successMessageAndData("登陆成功",user.getToken());
        httpServletResponse.setContentType("text/json;charset=utf-8");
        //登陆成功返回token
        httpServletResponse.getWriter().write(JSON.toJSONString(result));

    }




}
